package org.example.mvn;

import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.util.Collection;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Mojo(name = "cleanclass",defaultPhase = LifecyclePhase.CLEAN)
public class ClassCleanerMojo extends AbstractMojo {
    @Parameter(property = "cleaner.targetDir", defaultValue = "${project.build.directory}", readonly = true)
    private String targetDir;
    private Collection<File> findClassFiles(File dir) {
        return Stream.of(Objects.requireNonNull(dir.listFiles()))
                .flatMap(file -> file.isDirectory() ? findClassFiles(file).stream() : Stream.of(file))
                .filter(file -> file.isFile() && file.getName().endsWith(".class"))
                .collect(Collectors.toList());
    }
    @Override
    public void execute() throws MojoExecutionException {
        if(targetDir == null){
            throw new MojoExecutionException("targetDir is null");
        }else {
            File classDir = new File(targetDir + "/classes");
            if (classDir.exists()) {
                Collection<File> files = findClassFiles(classDir);
                getLog().info("Number of .class files to be cleaned: " + files.size());
                for (File file : files) {
                    if (file.delete()) {
                        getLog().info("Deleted: " + file.getName());
                    } else {
                        getLog().info("Failed to delete: " + file.getName());
                    }
                }
            }else {
                getLog().info("No .class files to be cleaned");
            }
        }
    }
}

